package com.zerlings.gabeisfaker.ui

import android.widget.Toast
import com.dbflow5.database.SQLiteException
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.zerlings.gabeisfaker.MyApplication.Companion.context
import com.zerlings.gabeisfaker.R
import com.zerlings.gabeisfaker.data.model.PriceBundle
import com.zerlings.gabeisfaker.data.repository.ItemRepository
import com.zerlings.gabeisfaker.data.repository.PriceRepository
import com.zerlings.gabeisfaker.data.repository.StatsRepository
import kotlinx.coroutines.Job
import retrofit2.HttpException
import java.io.IOException

class MainViewModel : BaseViewModel() {

    companion object {
        val priceMap = HashMap<String,String>()
    }

    private val statsRepository = StatsRepository

    private val priceRepository = PriceRepository

    private val itemRepository = ItemRepository

    var priceJob: Job? = null

    init {
        statsRepository.resetStats()
    }

    /**更新价格表*/
    fun updatePrices() {
        var response: PriceBundle? = null
        priceJob = launch({
            response = priceRepository.queryAllPrices()
            Toast.makeText(context, if (response?.status == "success") R.string.download_success else R.string.server_error, Toast.LENGTH_SHORT).show()
            priceRepository.storePriceData(response)
            response?.prices?.forEach { priceMap[it.market_hash_name] = it.price }
            val uniqueItemList = itemRepository.getUniqueItems()
            uniqueItemList.forEach { it.price = priceMap[it.marketHashName] ?: it.price }
            itemRepository.updateUniqueItems(uniqueItemList)
            Toast.makeText(context, R.string.update_success, Toast.LENGTH_SHORT).show()
        },{
            Toast.makeText(context, when (it){
                is IOException -> {
                    if (response == null) R.string.connection_error else R.string.update_error
                }
                is HttpException -> R.string.unknown_error
                is SQLiteException -> R.string.update_error
                else -> R.string.update_error
            }, Toast.LENGTH_SHORT).show()
            it.printStackTrace()
        })
    }

    /**载入价格表*/
    fun loadPrices() {
        priceJob = launch({
            val priceData = priceRepository.loadPriceData()
            Gson().fromJson(priceData, PriceBundle::class.java)?.takeIf { it.status == "success" }?.prices?.forEach {
                priceMap[it.market_hash_name] = it.price
            }
        },{
            when (it){
                is IOException -> {}
                is JsonSyntaxException -> {}
            }
            it.printStackTrace()
            Toast.makeText(context, R.string.load_error, Toast.LENGTH_LONG).show()
        })
    }

}